package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.dao.*;
import com.itheima.domain.*;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl
        extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 提交订单，购买
     *
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //13812345678
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //查询购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartMapper.selectList(wrapper);
        //查询用户数据
        User user = userMapper.selectById(userId);
        //根据地质id删除地址数据
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());

        //生成orderId(订单号... ... 很重要)
        long orderId = IdWorker.getId();

        //设置总价
        BigDecimal amount = new BigDecimal(0);

        //保存订单明细数据
        for (ShoppingCart shoppingCart : list) {
            //每个购物车数据，都可生产订单明细数据
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //特殊数据 orderId 和 amount(数量 * 单价)
            orderDetail.setOrderId(orderId);
            //shoppingCart.getAmount()  : 数量
            // multiply  :  乘法
            // shoppingCart.getName()  :  单价
            // BigDecimal  :  价格计算需要准确，所有使用 BigDecimal
            orderDetail.setAmount(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
            amount = amount.add(orderDetail.getAmount());
            //保存订单明细
            orderDetailMapper.insert(orderDetail);
        }
        //保存订单


//        //组装订单数据(直接拷贝的)
        orders.setId(orderId); // 订单id
        orders.setOrderTime(LocalDateTime.now()); // 订单创建时间
        orders.setCheckoutTime(LocalDateTime.now()); // 结账时间
        orders.setStatus(2); // 1、待支付   2、待派送
        // 3、已派送   4、已完成    5、已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId); // 用户id
        orders.setNumber(String.valueOf(orderId));// 订单号
        orders.setUserName(user.getName());// 用户名
        orders.setConsignee(addressBook.getConsignee());// 收货人
        orders.setPhone(addressBook.getPhone());// 收货人联系电话
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));// 省+市+区+地址

        //保存
        ordersMapper.insert(orders);

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        //清空购物车
        shoppingCartMapper.delete(wrapper);

        //13812345678


    }
}